package it.yuzuojian.com.config;


import it.yuzuojian.com.javaBean.User;
import it.yuzuojian.com.mapper.ShiroMapper;
import it.yuzuojian.com.util.RedisUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class MyRealm extends AuthorizingRealm  {
    @Autowired
    private ShiroMapper shiroMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public String getName() {
        return "userRealm";
    }


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String user = (String) principalCollection.iterator().next();
        Set<Object> roles_Test= new HashSet<>();
        Set<String> roles= new HashSet<>();
        if(redisUtil.hasKey(user+":roles")){
            roles_Test= redisUtil.sGet(user+":roles");
            for (Object o : roles_Test) {
                roles.add((String) o);
            }
        }else {
            roles = shiroMapper.queryRoleNamesByUsername(user);
            for (String role : roles) {
                redisUtil.sSet(user+":roles",role);
            }

        }
        Set<Object> permissions_Test= new HashSet<>();
        Set<String> permissions= new HashSet<>();
        if(redisUtil.hasKey(user+":permissions")){
            permissions_Test= redisUtil.sGet(user+":permissions");
            for (Object o : permissions_Test) {
                permissions.add((String) o);
            }
        }else {
            permissions = shiroMapper.queryPermissionsByUsername(user);
            for (String permission : permissions) {
                redisUtil.sSet(user+":permissions",permission);
                System.out.println(permission);
            }

        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(permissions);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String useName = token.getUsername();
        User user = shiroMapper.queryUserByUsername(useName);
        if (user == null) {
            return null;
        }
        AuthenticationInfo info = new SimpleAuthenticationInfo(user.getName(),
                user.getPassword(), ByteSource.Util.bytes("yuzuojian"), getName());
        return info;
    }
}
